package com.permission.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.permission.constant.UserStatusEnum;
import com.permission.dao.SysUserMapper;
import com.permission.exception.ParamException;
import com.permission.model.SysUser;
import com.permission.param.UserParam;
import com.permission.util.EnumUtil;
import com.permission.vo.SysUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2018/4/13
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public void save(UserParam userParam) {
        // 判断用户名是否已经被使用
        checkUsername(userParam.getUsername());

        // TODO 密码MD5加密

        // 保存用户
        SysUser sysUser = new SysUser();
        sysUser.setUsername(userParam.getUsername());
        sysUser.setPassword(userParam.getPassword());
        sysUser.setUserStatus(userParam.getUserStatus());
        int result = sysUserMapper.insertSelective(sysUser);
        if (result != 1) {
            throw new ParamException("新增用户失败");
        }
    }

    @Override
    public PageInfo list(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> sysUserList = sysUserMapper.selectListOrderByUserIdDesc();
        List<SysUserVo> sysUserVoList = sysUserList.stream().map(
            e -> {
                SysUserVo sysUserVo = new SysUserVo();
                BeanUtils.copyProperties(e, sysUserVo);
                sysUserVo.setUserStatusDesc(Objects.requireNonNull(
                        EnumUtil.getByCode(e.getUserStatus(), UserStatusEnum.class)).getMsg());
                return sysUserVo;
            }
        ).collect(Collectors.toList());
        return new PageInfo<>(sysUserVoList);
    }

    private void checkUsername(String username) {
        int result = sysUserMapper.countByUsername(username);
        if (result != 0) {
            throw new ParamException("用户名称已经存在");
        }
    }
}
